/**
 * 实现商品添加，查询，修改， 删除
 */
const express = require('express')
const { queryDBPromise } = require('../util/db')
const goodsRouter = express.Router() // 路由对象

/**
 * 商品添加
 *   method:POST
 *   url:/goods
 *   参数: name,price,num,url
 */
goodsRouter.post('/goods', (req, res) => {
	const name = req.body.name
	const price = req.body.price
	const num = req.body.num
	const url = req.body.url

	const sql = `INSERT INTO goods (name,price,num,url)VALUES('${name}',${price},${num},'${url}')`
	queryDBPromise(sql)
		.then(data => {
			res.send({
				code: 1,
				mesasge: '添加商品成功！',
			})
		})
		.catch(err => {
			res.send({
				code: -1,
				message: '添加商品失败!',
			})
		})
})

/**
 * 查看所有商品- 路由接口
 *   method: GET
 *   url: /goods
 *   参数： 无
 *   响应:  {code:1, list:[{id:1,name:'',price:'',num:,url}]}
 */
goodsRouter.get('/goods', (req, res) => {
	const sql = `SELECT id,name,price,num,url FROM goods`
	queryDBPromise(sql).then(data => {
		// data返回的商品数组
		if (data.length > 0) {
			res.send({
				code: 1,
				list: data,
			})
		} else {
			res.send({
				code: -1,
				message: '没有商品！',
			})
		}
	})
})


/**
 * 根据id查找商品
 */
goodsRouter.get('/goods/:id',(req,res)=>{
	const id = req.params.id 
	const sql = `SELECT id,name,url,price,num FROM goods WHERE id = ${id}`
	queryDBPromise(sql).then(data=>{
		const goods = data[0]
		res.send({
			code:1,
			goods
		})
	})
})


/**
 * 修改商品
 *   根据商品id修改商品的价格
 *   method: put
 *    url: /goods/:id      
 *           /goods/1      const id = req.parmas.id
 *    参数： id   price
 *    响应： {code:1, message: '修改成功!'}
 */
goodsRouter.put('/goods/:id', (req, res) => {
	const id = req.params.id //商品id
	const price = req.body.price //商品价格

	const sql = `UPDATE goods SET price = ${price} WHERE id = ${id}`
	queryDBPromise(sql).then(data => {
		//data:对象
		res.send({
			code: 1,
			message: '修改商品成功!',
		})
	})
})

/**
 * 删除商品
 *   根据商品id删除商品
 *    method:delete
 *    url:  /goods/1
 *    参数：id  params
 *    响应：{code:1,message:'删除成功'}
 */
goodsRouter.delete('/goods/:id', (req, res) => {
	const id = req.params.id // 商品id

	const sql = `DELETE FROM goods WHERE id = ${id}`
	queryDBPromise(sql).then(data => {
		res.send({
			code: 1,
			message: '删除成功!',
		})
	})
})

module.exports = { goodsRouter }
